import React, {useEffect, useState} from "react";
import {UserOutlined, LockOutlined, CheckCircleFilled, ReloadOutlined} from "@ant-design/icons";
import {message, notification} from "@/hooks/modules/useMessage";
import {Button, Form, Input, type FormInstance} from "antd";
import {useUserStore} from "@/store/user";
import {getTimeState} from "@/utils/tools";
import {usePermissions} from '@/hooks/modules/usePermissions'
import {useNavigate, useSearchParams} from "react-router";
import request from "@/service/request";

const LoginForm = () => {

    const navigate = useNavigate();
    const [searchParams] = useSearchParams()

    const {setToken} = useUserStore()
    const {initPermissions} = usePermissions();

    const formRef = React.useRef<FormInstance>(null);
    const [loading, setLoading] = useState<boolean>(false);

    const onFinish = async (value: { username: string, password: string }) => {
        try {
            setLoading(true);
            message.open({key: "loadKey", type: "loading", content: "登录中..."});
            const {data} = await request.post('/login', value) as unknown as Record<string, any>
            setToken(data.token)
            await initPermissions(data.token)
            setTimeout(() => {
                notification.success({
                    message: getTimeState(),
                    description: `欢迎登录 ${data.userInfo.name}`,
                    icon: <CheckCircleFilled style={{color: "#73d13d"}}/>
                });
            }, 300)
            navigate(searchParams.get('redirect') || '/home', {replace: true})
        } finally {
            setLoading(false);
            message.destroy("loadKey");
        }
    }
    const onReset = () => {
        formRef.current?.resetFields();
    };

    useEffect(() => {
        document.onkeydown = event => {
            if (event.code === "Enter") {
                event.preventDefault();
                formRef.current?.submit();
            }
        };
        return () => {
            document.onkeydown = () => {
            };
        };
    }, []);

    return (
        <div className="[&_.ant-form-item]:mb-[35px]">
            <Form name="login" size="large" autoComplete="off" ref={formRef} onFinish={onFinish}>
                <Form.Item name="username" rules={[{required: true, message: "请输入用户名"}]}>
                    <Input prefix={<UserOutlined/>} placeholder="请输入用户名"/>
                </Form.Item>
                <Form.Item name="password" rules={[{required: true, message: "请输入密码"}]}>
                    <Input.Password prefix={<LockOutlined/>} placeholder="请输入密码"/>
                </Form.Item>
                <Form.Item
                    className="w-full [&_.ant-btn]:w-[45%] [&_.ant-form-item-control-input-content]:flex [&_.ant-form-item-control-input-content]:justify-between [&_.ant-form-item-control-input-content]:items-center">
                    <Button type="primary" shape="round" icon={<UserOutlined/>}
                            loading={loading} htmlType="submit">
                        登录
                    </Button>
                    <Button shape="round" icon={<ReloadOutlined/>} onClick={onReset}>
                        重置
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
};

export default LoginForm;
